<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工号" prop="jobNumber">
        <el-input v-model="queryParams.jobNumber" placeholder="请输入工号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:outlets:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:outlets:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:outlets:del']">批量删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="适用区域" align="center" :show-overflow-tooltip="true" prop="regionName" width="120" />
      <el-table-column label="适用门店" align="center" prop="storeName" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="工号" align="center" prop="jobNumber" />
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="底薪" align="center" prop="basicSalary" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == '1' ? '在职' : '离职 ' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200px" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:outlets:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleGround(scope.row, status = 2)"
            :disabled="scope.row.status === 2">离职</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:outlets:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="regionId">
              <el-select clearable v-model="form.regionId" @change='changeRegion'>
                <el-option v-for="(item, index) of region" :key="index" :label="item.value"
                  :value="item.key">{{ item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用门店" prop="storeId">
              <el-select clearable v-model="form.storeId" @change='changeStore'>
                <el-option v-for="(item, index) of store" :key="index" :label="item.value"
                  :value="item.key">{{ item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入姓名" style="width: 222px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话" style="width: 222px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工号" prop="jobNumber">
              <el-input v-model="form.jobNumber" placeholder="请输入工号" style="width: 222px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="底薪" prop="basicSalary">
              <el-input v-model="form.basicSalary" placeholder="请输入底薪" style="width: 222px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否在职" prop="status">
          <el-select clearable v-model="form.status" style="width: 222px;">
            <el-option v-for="(item, index) of List" :key="index" :label="item.value"
              :value="item.key">{{ item.value }}</el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listmanager, getItemProduct, delitemProduct, addItemManager, updateitemProduct, listMemberRegion, listMemberStore } from "@/api/system/personnel/outlets";

export default {
  name: "Store",
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: '',
      longitude: '',
      keyWords: '',
      result: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobNumber: null,
        productName: null,
        storeName: null,
        userName: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        regionId: [
          { required: true, message: '请选择所属区域', trigger: 'blur' },
        ],
        storeId: [
          { required: true, message: '请选择适用门店', trigger: 'blur' },
        ],
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1到 10 个字符', trigger: 'blur' }
        ],
        jobNumber: [
          { required: true, message: '请输入正确的工号', trigger: 'blur' },
          { pattern: /^-?\d+(\.\d+)?$/, message: '请输入正确的工号', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        basicSalary: [
          { required: true, message: '请输入底薪', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '底薪必须为数字', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择上架', trigger: 'blur' },
        ],
      },
      options: [],
      List: [
        {
          key: 1,
          value: '在职'
        },
        {
          key: 2,
          value: '离职'
        },
      ],
      region: [],
      store: [],
    };
  },
  created() {
    this.getList();
    this.listregion()
    listMemberStore().then(res => {
      console.log(res, 333);
      this.store = res.data.map(rItem => {
        return {
          key: rItem.id,
          value: rItem.storeName,
        }
      })
    })
  },
  methods: {
    listregion() {
      listMemberRegion().then(res => {
        this.region = res.data.map(rItem => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          }
        })
      })
    },
    changeRegion(value) {
      const selectedOption = this.region.find(item => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.regionName = selectedValue
      listMemberStore({ regionId: value }).then(res => {
        console.log(res, 333);
        this.store = res.data.map(rItem => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          }
        })
      })
    },
    changeStore(value) {
      const selectedOption = this.store.find(item => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.storeName = selectedValue
      console.log(this.form.storeName, 555);
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listmanager(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店管理员";
    },
    // 上下架
    handleGround(row, status) {
      const params = {
        id: row.id,
        status: status
      }
      this.$confirm(`此操作将${status === 1 ? '离职' : '下架'}该数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateitemProduct(params).then((res) => {
          this.$message({
            type: 'success',
            message: `${status === 1 ? '上架' : '下架'}成功!`
          });
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消上离职'
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItemProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改门店管理员";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateitemProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItemManager(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认重置编号为"' + ids + '"的数据项？').then(function () {
        return listResetPwd({ userId: ids });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重置成功");
      }).catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return delitemProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.dialog-footer {
  text-align: center;
}
</style>